//
//  ViewController.m
//  123
//
//  Created by Apple on 2017/7/7.
//  Copyright © 2017年 闪电极送. All rights reserved.
//

#import "ViewController.h"
#import "ButtonSwitchView.h"
#import "AFNetworking.h"
#import "Additions.h"
#import "ContentTableViewCell.h"
#import "ContentModel.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonHMAC.h>



// 只要添加了这个宏，就不用带mas_前缀
 #define MAS_SHORTHAND
 // 只要添加了这个宏，equalTo就等价于mas_equalTo
 #define MAS_SHORTHAND_GLOBALS
 // 这个头文件一定要放在上面两个宏的后面
#import "Masonry.h"
#import <ReactiveCocoa/ReactiveCocoa.h>
#define ImgDuanKou  @"http://192.168.31.101:10086/"

@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSArray *datas;
    UITableView *tableview;
    OSSClient * client;
    
    NSString *photoUrl;
    
    NSString *AccessKeyId ;
    NSString *AccessKeySecret ;
    NSString *SecurityToken ;
    NSString *time;
}
@property(nonatomic,strong)NSData *imageData;
@property(nonatomic,strong)NSMutableArray *yuyueArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
//    UILabel *lab = [[UILabel alloc] init];
//    lab.frame =CGRectMake(50, 50, 30, 20);
//    [self.view addSubview:lab];
//    lab.backgroundColor = [UIColor blueColor];
//    lab.text = @"我的中ASSSSSSSSSSSSS国心CHANGIANGHAUANGHEZAIWOXINZHINGAN";
//    [lab sizeToFit];
    
    
    
    self.yuyueArray = [NSMutableArray new];
    
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    NSString *url = [NSString stringWithFormat:@"%@api/Train/Available?runningId=%@",ImgDuanKou,@"2746034"];
//    [session GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *dic = (NSDictionary *)responseObject;
//       // self.yuyueArray = dic[@"trains"];
//        for (NSDictionary *dic1 in dic[@"trains"]) {
//            ContentModel *contentModel = [ContentModel new];
//            contentModel.addressStr = dic1[@"address"];
//            contentModel.contentStr = dic1[@"content"];
//            [self.yuyueArray addObject:contentModel];
//            
//            NSLog(@"11101111 %@  %@",contentModel.addressStr,contentModel.contentStr);
//        }
//        
//        [tableview reloadData];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
    
    
//    ButtonSwitchView *viewButton = [[ButtonSwitchView alloc] init];
//    viewButton.frame = CGRectMake(0, 100,self.view.frame.size.width, 50);
//    viewButton.tag = 1000;
//    
//    [[RACObserve(viewButton, status)skip:1] subscribeNext:^(id x)
//     {
//         NSLog(@"%ld",(long)[x integerValue]);
//         if ([x integerValue]==0) {
//             
//                         
//             NSLog(@"热门推荐数据");
//             //[self loadImagePicker];
//             //[self BGview];
//         }
//         else if ([x integerValue]==1)
//         {
//             NSLog(@"最高收益数据");
//             
//         }
//         else if ([x integerValue]==2)
//         {
//             NSLog(@"当日返现数据");
//         }
//         else if ([x integerValue]==3)
//         {
//             NSLog(@"风控得分数据");
//         }
//     }];
//    [self.view addSubview:viewButton];
    
    
//    [[RACObserve(viewButton, status) skip:1] subscribeNext:^(id x) {
//        if ([x integerValue] == 0) {
////            datas = [NSArray yy_modelArrayWithClass:[MainPageDataMode class] json:[((ModulesModel *)self.dataSources).data objectForKey:@"websites"]];
//        }else{
////            datas = [NSArray yy_modelArrayWithClass:[MainPageDataMode class] json:[((ModulesModel *)self.dataSources).data objectForKey:@"brands"]];
//        }
////        isBrand = [x integerValue];
////        [UIView transitionWithView:self.cellCollectionView duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
////            [self.cellCollectionView reloadData];
//        } completion:^(BOOL finished) {
//            
//        }];
//    }];
//    [self.view addSubview:viewButton];
//    [viewButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
//    }];

    
    
//   tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
//    tableview.delegate =self;
//    tableview.dataSource =self;
//    [self .view addSubview:tableview];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(100, 100, 100, 100);
    btn.backgroundColor =[UIColor redColor];
    [btn addTarget:self action:@selector(upImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

/**
 *  按钮事件
 */
- (void)upImage
{
    [self loadImagePicker];
    
}
-(void)loadImagePicker
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate                 = self;
    picker.sourceType               = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing            = YES;
    [self presentViewController:picker animated:YES completion:NULL];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *avatar = info[UIImagePickerControllerOriginalImage];
    //处理完毕，回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:NULL];
    //判断图片是不是png格式的文件
    if (UIImagePNGRepresentation(avatar)) {
        //返回为png图像。
        UIImage *imagenew = [self imageWithImageSimple:avatar scaledToSize:CGSizeMake(200, 200)];
        self.imageData = UIImagePNGRepresentation(imagenew);
    }else {
        //返回为JPEG图像。
        UIImage *imagenew = [self imageWithImageSimple:avatar scaledToSize:CGSizeMake(200, 200)];
        self.imageData = UIImageJPEGRepresentation(imagenew, 0.1);
    }
    
    
    [self requestToken];
    
    

}

//获得token
- (void)requestToken
{
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    NSDate *guoqiDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"expiration"];
    NSLog(@"%@",guoqiDate);
    
    NSComparisonResult result = [[NSDate date]compare:guoqiDate];
    
    if (token != nil && result== NSOrderedAscending) {
        
        [self startUploadaccessKeyId:AccessKeyId accessKeySecret:AccessKeySecret token:token];
    }
    else
    {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:@"http://192.168.31.101:10087/api/aliyun/token" parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic = (NSDictionary *)responseObject;
            
            NSDictionary *dic1 = dic[@"data"];
            AccessKeyId = dic1[@"accessKeyId"];
            AccessKeySecret = dic1[@"accessKeySecret"];
            SecurityToken = dic1[@"securityToken"];
            
            
            
            //NSDate *Timedata = [NSDate dateFromString:dic1[@"expiration"] withFormat:@"yyyy-MM-dd HH:mm:ss"];
            // 时间字符串
            
                        NSString *timeString = dic1[@"expiration"];
            
                        // 日期格式化类
            
                        NSDateFormatter *format = [[NSDateFormatter alloc] init];
            
                        // 设置日期格式 为了转换成功
            
                        format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            
                        // NSString * -> NSDate *
            
                        NSDate *Timedata = [format dateFromString:timeString];
            
            
            
            [[NSUserDefaults standardUserDefaults] setObject:SecurityToken forKey:@"token"];
            //时间转成date ，存到本地（注意！！！）
            [[NSUserDefaults standardUserDefaults] setObject:Timedata forKey:@"expiration"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [self startUploadaccessKeyId:AccessKeyId accessKeySecret:AccessKeySecret token:SecurityToken];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
        
    }
    
}


- (void)startUploadaccessKeyId:(NSString *)accessKeyId  accessKeySecret:(NSString *)accessKeySecret  token:(NSString *)accessToken
{
    NSString *endpoint = @"oss-cn-beijing.aliyuncs.com";
    // 移动端建议使用STS方式初始化OSSClient。更多鉴权模式请参考后面的访问控制章节。
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:accessToken];
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // required fields
#warning 参数设置
    put.bucketName = @"sdjs-order-images";
    NSString *objectKeys = [NSString stringWithFormat:@"IOSUser/%@.jpg",[self getTimeNow]];
    
    put.objectKey = objectKeys;
    
    put.uploadingData = self.imageData;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {
        task = [client presignPublicURLWithBucketName:@"sdjs-order-images" withObjectKey:objectKeys];
        
        if (!task.error) {
            //IOSUser/20170805181139462-6112.jpg
            photoUrl = [NSString stringWithFormat:@"http://sdjs-order-images.oss-cn-beijing.aliyuncs.com/%@",objectKeys];
            NSLog(@"objectKey: %@", photoUrl);
            
            
            
            [self uploadUrl];
            
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    
}

//把上传图片地址传给后台
- (void)uploadUrl
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *parameters = @{
                                 @"OrderId":@"N2N6LJP4064VTJX4",
                                 @"PhotoUrl":photoUrl,
                                 @"RunnerId":@"2746034"
   
                                 };
    
                [manager POST:@"http://192.168.31.101:10087/api/order/uploadphoto" parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    
    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic2 = (NSDictionary *)responseObject;
                    NSLog(@"dic2  111 %@",dic2);
    
    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
    

}
- (UIImage *)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%i", date,last];
    NSLog(@"%@", timeNow);
    return timeNow;
}
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    return _yuyueArray.count;
//}
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//   // NSDictionary *dic ;
//    static NSString *cellID = @"cell";
//    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
//    if (cell == nil) {
//        cell = [[ContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
//    }
//    ContentModel *contentModel = [[ContentModel alloc] init];
//    //dic = _yuyueArray[indexPath.row];
//    contentModel = _yuyueArray[indexPath.row];
//    cell.contentLab.text = contentModel.contentStr;
//    return cell;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    ContentModel *contentModel = _yuyueArray[indexPath.row];
//    //NSString *content = dic[@"content"];
//    CGFloat height =  [ContentTableViewCell getHeightContent:contentModel.contentStr];
//    return height;
//    
//}
-(void)BGview
{
//    UIView *sv = [UIView new];
//    sv.backgroundColor = [UIColor  redColor];
//    [self.view addSubview:sv];
//    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.center.mas_equalTo(self.view);
//        make.size.mas_equalTo(CGSizeMake(200, 200));
//        //make.top.left.bottom.right.mas_equalTo(self.view);
//    }];
    
    UILabel *lab = [UILabel new];
    lab.backgroundColor = [UIColor redColor];
    lab.textColor = [UIColor whiteColor];
    [self.view addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(100, 40));
    }];
    
    
    
    //__weak typeof(self) weakSelf = self;
    // 剩余的时间（必须用__block修饰，以便在block中使用）
    __block NSInteger remainTime = 5;
    // 获取全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    // 每隔1s钟执行一次
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    // 在queue中执行event_handler事件
    dispatch_source_set_event_handler(timer, ^{
        if (remainTime <= 0) { // 倒计时结束
            dispatch_source_cancel(timer);
            // 回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                //weakSelf.enabled = YES;
               // completion(weakSelf);
                lab.text = @"抢单";
            });
        } else {
            NSString *timeStr = [NSString stringWithFormat:@"%ld", remainTime];
            // 回到主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                lab.text = timeStr;
//                [weakSelf setTitle:[NSString stringWithFormat:@"%@%@",timeStr,unitTitle] forState:UIControlStateDisabled];
//                [weakSelf setBackgroundImage:[UIImage createImageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
//                weakSelf.enabled = NO;
            });
            remainTime--;
        }
    });
    dispatch_resume(timer);
    
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
